class CustomerServiceChat {
    constructor() {
        this.socket = null;
        this.userId = this.generateUserId();
        this.userType = 'user';
        this.reconnectAttempts = 0;
        this.maxReconnectAttempts = 5;
        this.reconnectDelay = 3000;
        
        this.initElements();
        this.initEventListeners();
        this.connectWebSocket();
    }

    generateUserId() {
        return 'user_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
    }

    initElements() {
        this.chatMessages = document.getElementById('chatMessages');
        this.messageInput = document.getElementById('messageInput');
        this.sendButton = document.getElementById('sendButton');
        this.charCount = document.getElementById('charCount');
        this.connectionStatus = document.getElementById('connectionStatus');
        this.statusText = this.connectionStatus.querySelector('.status-text');
    }

    initEventListeners() {
        this.sendButton.addEventListener('click', () => this.sendMessage());
        this.messageInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                this.sendMessage();
            }
        });

        this.messageInput.addEventListener('input', () => {
            this.updateCharCount();
            this.sendButton.disabled = !this.messageInput.value.trim();
        });

        // 页面关闭时断开连接
        window.addEventListener('beforeunload', () => {
            this.disconnect();
        });
    }

    connectWebSocket() {
        try {
            const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
            const wsUrl = `${protocol}//${window.location.host}/websocket/chat?userId=${this.userId}&userType=${this.userType}`;
            
            this.socket = new WebSocket(wsUrl);
            
            this.socket.onopen = () => {
                console.log('WebSocket连接已建立');
                this.reconnectAttempts = 0;
                this.updateConnectionStatus('connected', '已连接');
                this.sendJoinMessage();
            };

            this.socket.onmessage = (event) => {
                this.handleMessage(event.data);
            };

            this.socket.onclose = (event) => {
                console.log('WebSocket连接已关闭', event);
                this.updateConnectionStatus('disconnected', '连接断开');
                this.handleReconnect();
            };

            this.socket.onerror = (error) => {
                console.error('WebSocket错误:', error);
                this.updateConnectionStatus('disconnected', '连接错误');
                this.addSystemMessage('连接出现错误，请刷新页面重试');
            };

        } catch (error) {
            console.error('WebSocket连接失败:', error);
            this.updateConnectionStatus('disconnected', '连接失败');
            this.addSystemMessage('无法连接到客服系统，请稍后重试');
        }
    }

    sendJoinMessage() {
        const joinMessage = {
            type: 'join',
            userId: this.userId,
            userType: this.userType,
            timestamp: Date.now()
        };
        this.socket.send(JSON.stringify(joinMessage));
    }

    handleMessage(data) {
        try {
            const message = JSON.parse(data);
            
            switch (message.type) {
                case 'chat':
                    this.addChatMessage(message);
                    break;
                case 'system':
                    this.addSystemMessage(message.content);
                    break;
                case 'adminJoined':
                    this.addSystemMessage('客服已加入对话');
                    break;
                case 'adminLeft':
                    this.addSystemMessage('客服已离开对话');
                    break;
            }
        } catch (error) {
            console.error('消息解析错误:', error);
        }
    }

    sendMessage() {
        const content = this.messageInput.value.trim();
        if (!content || !this.socket || this.socket.readyState !== WebSocket.OPEN) {
            return;
        }

        const message = {
            type: 'chat',
            userId: this.userId,
            userType: this.userType,
            content: content,
            timestamp: Date.now()
        };

        this.socket.send(JSON.stringify(message));
        this.messageInput.value = '';
        this.updateCharCount();
        this.sendButton.disabled = true;
    }

    addChatMessage(message) {
        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${message.userType}`;
        
        const contentDiv = document.createElement('div');
        contentDiv.className = 'message-content';
        contentDiv.textContent = message.content;
        
        const timeDiv = document.createElement('div');
        timeDiv.className = 'message-time';
        timeDiv.textContent = this.formatTime(message.timestamp);
        
        messageDiv.appendChild(contentDiv);
        messageDiv.appendChild(timeDiv);
        
        this.chatMessages.appendChild(messageDiv);
        this.scrollToBottom();
    }

    addSystemMessage(content) {
        const messageDiv = document.createElement('div');
        messageDiv.className = 'system-message';
        messageDiv.innerHTML = `
            <div style="text-align: center; margin: 20px 0;">
                <span style="background: rgba(0,0,0,0.1); color: #666; padding: 8px 16px; border-radius: 12px; font-size: 12px;">
                    ${content}
                </span>
            </div>
        `;
        
        this.chatMessages.appendChild(messageDiv);
        this.scrollToBottom();
    }

    updateCharCount() {
        const length = this.messageInput.value.length;
        this.charCount.textContent = length;
        
        if (length > 450) {
            this.charCount.style.color = '#ef4444';
        } else if (length > 400) {
            this.charCount.style.color = '#f59e0b';
        } else {
            this.charCount.style.color = '#9ca3af';
        }
    }

    updateConnectionStatus(status, text) {
        this.connectionStatus.className = `connection-status ${status}`;
        this.statusText.textContent = text;
        
        if (status === 'connected') {
            setTimeout(() => {
                this.connectionStatus.classList.add('hidden');
            }, 2000);
        } else {
            this.connectionStatus.classList.remove('hidden');
        }
    }

    handleReconnect() {
        if (this.reconnectAttempts < this.maxReconnectAttempts) {
            this.reconnectAttempts++;
            this.updateConnectionStatus('disconnected', `正在重连... (${this.reconnectAttempts}/${this.maxReconnectAttempts})`);
            
            setTimeout(() => {
                this.connectWebSocket();
            }, this.reconnectDelay);
        } else {
            this.updateConnectionStatus('disconnected', '连接失败');
            this.addSystemMessage('连接失败，请刷新页面重试');
        }
    }

    formatTime(timestamp) {
        const date = new Date(timestamp);
        return date.toLocaleTimeString('zh-CN', { 
            hour: '2-digit', 
            minute: '2-digit' 
        });
    }

    scrollToBottom() {
        this.chatMessages.scrollTop = this.chatMessages.scrollHeight;
    }

    disconnect() {
        if (this.socket) {
            this.socket.close();
            this.socket = null;
        }
    }
}

// 页面加载完成后初始化聊天功能
document.addEventListener('DOMContentLoaded', () => {
    new CustomerServiceChat();
});